import { defineStore } from "pinia"; // 定义仓库
import { login, logout, userInfo, routers } from "@/api/user";
import router from "@/router/router";

// 创建用户仓库
export const useUser = defineStore("userStore", {
  // 存放所有用户相关的状态
  state: () => {
    return {
      user: {}, // 用户信息
      counter: 0,
      token: undefined,
    };
  },
  // 获取state中的状态
  getters: {
    doubleCount: (state) => state.counter * 2,
  },
  // 设置state中的状态可以用异步函数获取互联网上的资源
  actions: {
    // 获取用户信息
    getUser() {
      return new Promise((resolve, reject) => {
        var token = localStorage.getItem("userToken");
        if("null" == token){
          router.push({path: "/login"})
        }else{
        // 异步操作 调用登录api
        // 保存登录token
        var tokenForm = {};
        tokenForm.token = token;
        userInfo(tokenForm).then((res) => {
          if(res.status==400){
            localStorage.setItem("userToken",null);
            this.$router.replace("/login");
          }
          //存储用户信息
          //用户数据
          //用户的角色
          //用户的权限码
          console.log(res);
          resolve();
        });}
      });
    },
    getRouters() {
      return new Promise((resolve, reject) => {
        var token = localStorage.getItem("userToken");
        var tokenForm = {};
        tokenForm.token = token;
        routers(tokenForm).then((res) => {
          console.log("routers", res);
          //封装一个路由对象
          this.filterRouters(res.data);
          resolve(res);
        });
      });
    },
    filterRouters(routers) {
      let routersFilter = [];
      routers.forEach((router) => {
        let routerFilter = {};
        if (router.menuType == 0) {
          routerFilter.component = import("@/components/Main.vue");
        } else {
          routerFilter.component = import("@/views/" + router.menuUrl + ".vue");
        }
        routerFilter.path = router.path;
        if (router.children) {
          routerFilter.children = filterRouters(router.children);
        }
        routersFilter.put(routerFilter);
      });
      return routersFilter;
    },
    // 登录
    async doLogin(params) {
      return await new Promise((resolve, reject) => {
        // 异步操作
        login(params).then((res) => {
          console.log(res);
          //保存登录token
          this.token = res.data;
          // todo
          localStorage.setItem("userToken", this.token);
          resolve(res);
        });
      });
    },
    setCounter(num) {
      this.counter = num;
    },
  },
});
